<?php
	// INCLUDES
	include('config.php'); 
	
	// Get the search variable from URL
	
	$var = @$_GET['q'] ;
	$trimmed = trim($var); //trim whitespace from the stored variable
			
	// rows to return
	$limit=2; 
	
	// check for an empty string and display a message.
	if ($trimmed == "")
	{
		echo "<p>Erro na busca, retorne a página de pesquisa...</p>";
		exit;
	}
	
		
	// Build SQL Query  
	//$query = "SELECT * FROM tbartifacts WHERE Title LIKE \"%$trimmed%\" OR Text LIKE \"%$trimmed%\" " ; 
	
	$query_aux = " (SELECT tbTags.Fkidartifacts
	               FROM tbtags
	               WHERE  tbtags.Tagname LIKE \"%$trimmed%\" )" ;
	
	$query = "SELECT tbartifacts.Id, tbartifacts.Title, tbartifacts.Text, tbartifacts_type.Name, 
	          tbusers.Name AS Author
			  FROM tbartifacts, tbartifacts_type, tbusers 
			  WHERE
				(tbartifacts.Title LIKE \"%$trimmed%\" OR tbartifacts.Text LIKE \"%$trimmed%\" OR
				 tbartifacts.Id IN {$query_aux})
			  AND tbartifacts.Type = tbartifacts_type.Id AND tbartifacts.Author = tbusers.Id";
	
		
	mysql_query("set names utf8");
	 
	$numresults = mysql_query($query);
	 
	if (!$numresults) 
	{
		die('Invalid query: ' . mysql_error());		
	}
	 
	$numrows = mysql_num_rows($numresults);
	
	// Writing the table with the query results. 
	echo ("<tbody>");
		 
	while ($row = mysql_fetch_assoc($numresults)) 
	{   		
		echo ("<tr>");	
		echo ("<td> <a href='download.php?id=" . $row["Id"] .   " '> " . $row["Title"] . " </a> </td>");
		echo ("<td>" . $row["Text"] . "</td>");
		echo ("<td>" . $row["Name"] . "</td>");
		echo ("<td>" . $row["Author"] . "</td>");
		echo ("</tr>");	
			
	}// while
	
	echo ("</tbody>");
	
	// Table Foot 
	echo ("<tfoot>");
		echo ("<tr>");
			echo ("<td colspan='4'>" . $numrows . " resultados encontrados</td>");
		echo ("</tr>");
	echo ("</tfoot>");
	
	
	// If we have no results, offer a google search as an alternative
	
	if ($numrows == 0)
	{
		//echo "<h4>Results</h4>";
		//echo "<p>Sorry, your search: &quot;" . $trimmed . "&quot; returned zero results</p>";
	}//if
	
	  
?>